package org.example.booksmanagementsystem.service;

import lombok.extern.slf4j.Slf4j;
import org.example.booksmanagementsystem.enums.BookInfoStatusEnum;
import org.example.booksmanagementsystem.mapper.BookInfoMapper;
import org.example.booksmanagementsystem.model.BookInfo;
import org.example.booksmanagementsystem.model.PageRequest;
import org.example.booksmanagementsystem.model.PageResult;
import org.example.booksmanagementsystem.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;
@Slf4j
@Service
public class BookInfoService {

    @Autowired
    private BookInfoMapper bookInfoMapper;

    public PageResult<BookInfo> getBookInfoListByPage(PageRequest pageRequest) {
        if(pageRequest==null){
            return null;
        }

        //获取表中数据的总数
        Integer count = bookInfoMapper.queryBookInfoCount();

        //获取该页的数据
        List<BookInfo> bookInfoList = bookInfoMapper.queryBookInfoByPage(pageRequest);

        //根据status 修改 statusCN
        for(BookInfo it : bookInfoList){

            // 使用枚举类设置图书的状态
            it.setStatusCN(BookInfoStatusEnum.getNameByCode(it.getStatus()).getName());
        }

        // 创建PageResult对象返回给Controller
        return new PageResult<BookInfo>(count,bookInfoList,pageRequest);

    }


    //添加图书
    public void addBookInfo(BookInfo bookInfo) {
        bookInfoMapper.insertBookInfo(bookInfo);
    }

    // 根据Id获取信息
    public BookInfo queryBookInfoById(Integer id){

        BookInfo bookInfo = null;

        try{
            bookInfo=bookInfoMapper.queryBookInfoById(id);
        }catch(Exception e){
            log.error("Service根据Id查询BookInfo报错 e{}："+e);
        }

        return bookInfo;
    }

    //修改BookInfo
    public Integer updateBookInfo(BookInfo bookInfo) {
        return bookInfoMapper.updateBookInfo(bookInfo);
    }

    //批量删除
    public Integer batchDeleteBookInfoById(List<Integer> idList) {
        return bookInfoMapper.batchDeleteBookInfoById(idList);
    }

    // 用户购买图书
    @Transactional
    public boolean buyBook(Integer bookId, UserInfo userInfo) {
        /*
        * 1.查询图书的库存
        * 2.减少图书的库存
        * 3.创建查询bookInfo
        * 4.查询是否购买过该图书
        * 5.购买过图书--count+1
        * 6.没有购买图书--向用户表中插入bookInfo，count为购买数量
        * */

        //判断图书是否有售卖库存
        log.info("判断是否有售卖库存");
        Integer count = bookInfoMapper.queryBookCount(bookId);
        if(count > 0){
            bookInfoMapper.deleteBookCount(bookId); // 库存减少
        }else{
            return false;
        }


        //查询bookInfo
        BookInfo bookInfo = bookInfoMapper.queryBookInfoById(bookId);

        //查询是否购买过该图书
        log.info("查询是否购买过图书");
        BookInfo buyBookInfo = bookInfoMapper.queryBookInfoByBookName(userInfo.getId(),bookInfo.getBookName());
        // 没有购买过图书
        if(buyBookInfo == null){
            // 没有购买过图书，向用户图书表中插图图书信息--count=1
            Integer n = bookInfoMapper.insertUserBookInfoTable(userInfo.getId(),bookInfo);

            // 插入成功后返回的结果为1
            if(n==1){
                return true;
            }else{
                return false;
            }
        }

        //购买过图书，count+1
        Integer n2 = bookInfoMapper.addCountUserBookInfoTable(userInfo.getId(),bookInfo.getBookName());
        if(n2==1){
            return true;
        }else{
            return false;
        }

    }

    // 取消购买图书
    @Transactional
    public boolean noBuyBook(Integer bookId, UserInfo userInfo) {
        /*
         * 1.查询bookInfo
         * 2.查询是否购买过该图书
         * 3.没有购买图书--返回false
         * 4.购买过图书--
         * 5.检查检查图书的count==0
         * 5.count >0 售卖图书库存+1， 用户图书count-1
         * */

        log.info("取消购买的Service");
        //查询bookInfo
        BookInfo bookInfo = bookInfoMapper.queryBookInfoById(bookId);

        //查询是否购买过该图书
        BookInfo buyBookInfo = bookInfoMapper.queryBookInfoByBookName(userInfo.getId(),bookInfo.getBookName());

        // 没有购买过图书
        if(buyBookInfo == null){
            log.info("没有购买过该图书");
            return false;
        }

        //购买过图书
        if(buyBookInfo.getCount() ==0){
            return false;

        }else{
            // 增加图书的售卖库存
            bookInfoMapper.addBookCount(bookId); // 库存减少
            log.info("增加销售库存");

            //减少用户图书的库存
            bookInfoMapper.deleteUserBookInfoCount(userInfo.getId(),bookInfo.getBookName()); // 库存增加
            return true;
        }

    }

    //批量购买图书
    @Transactional
    public boolean batchPurchaseBook(List<Integer> idList,UserInfo userInfo){

        for(Integer bookId : idList){
            buyBook(bookId,userInfo);
        }

        return true;
    }

    //用户购物车
    public PageResult<BookInfo> getBookInfoListOfNormalUserByPage(PageRequest pageRequest, UserInfo userInfo) {
        if(pageRequest==null){
            return null;
        }

        //获取表中数据的总数
        Integer count = bookInfoMapper.queryBookInfoCountOfNormalUser(userInfo.getId());

        //获取该页的数据
        List<BookInfo> bookInfoList = bookInfoMapper.queryBookInfoOfNormalUserByPage(pageRequest,userInfo.getId());

        //根据status 修改 statusCN
        for(BookInfo it : bookInfoList){

            // 使用枚举类设置图书的状态
            it.setStatusCN(BookInfoStatusEnum.getNameByCode(it.getStatus()).getName());
        }

        // 创建PageResult对象返回给Controller
        return new PageResult<BookInfo>(count,bookInfoList,pageRequest);

    }

    @Transactional
    public boolean noBuyOfNormalUser(Integer bookId,Integer userId){
        /*
        * 1.从用户图书中根据id查询图书的信息
        * 2.count>0 减去1
        * 3.根据图书名字，添加售卖图书的count+1
        * 4.
        * */

        BookInfo bookInfo = bookInfoMapper.queryBookInfoByNormalId(bookId,userId);
        if(bookInfo.getCount()<=0){
            return false;
        }

        // 已购买的书数量 -1
        Integer n1 = bookInfoMapper.deleteUserBookInfoCount(userId,bookInfo.getBookName());

        // 售卖书的库存 +1
        Integer n2 =bookInfoMapper.addBookCountByBookinfo(bookInfo);

        if(n1 ==0 || n2 == 0){

            throw new RuntimeException("在购物车中取消购买失败");
        }

        return true;
    }

    @Transactional
    public boolean batchNoBuyBook(List<Integer> idList, UserInfo userInfo){

        // 调用 Service -- noBuyOfNormalUser(Integer bookId,Integer userId)

        //取消购买
        for(Integer id : idList){
            noBuyOfNormalUser(id,userInfo.getId());
        }

        return true;
    }

    @Transactional
    public boolean buyOfshoppingTrolly(Integer bookId, UserInfo userInfo){
        /*
         1.从用户图书中获取图书信息
        * 2.用图书的名字 检查售卖图书是否有库存
        * 3.售卖图书库存减 +1
          4.用户图书count +1
        * */
        // 从用户图书获取信息
        BookInfo bookInfo = bookInfoMapper.queryBookInfoByNormalId(bookId, userInfo.getId());

        //查询售卖图书的信息
        BookInfo bookInfoSale = bookInfoMapper.queryBookInfoByBookInfo(bookInfo);
        if(bookInfoSale==null || bookInfoSale.getCount()<=0){
            throw new RuntimeException("在购物车中购买失败");
        }

        // 调用Service buyBook(Integer bookId, UserInfo userInfo)

        boolean b = buyBook(bookInfoSale.getId(),userInfo);

//        // 售卖图书减1
//        Integer n = bookInfoMapper.deleteBookCount(bookInfoSale.getId());
//        if(n==0){
//            throw new RuntimeException("在购物车中购买失败");
//        }
//
//        // 用户图书 count +1
//        Integer n2 = bookInfoMapper.addBookCountByBookinfo(bookInfo);

        return b;
    }
}


